package com.richard.home.viewModel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.richard.base.module.LiveDataModel
import com.richard.base.net.bean.KsResult
import com.richard.base.ui.BaseViewModel
import com.richard.home.model.bean.PoetryDetail
import com.richard.home.model.bean.PoetryWord
import com.richard.home.model.repository.HomeRepositoryImpl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class HomePicDetailViewModelImpl(val repository: HomeRepositoryImpl): HomePicDetailViewModel, BaseViewModel() {

    private val _uiState = MutableLiveData<LiveDataModel<PoetryDetail>>()

    val uiState : LiveData<LiveDataModel<PoetryDetail>> get() = _uiState

    override fun getPoetryDetail(poetryId: Int) {
        viewModelScope.launch(Dispatchers.Default){
            val ksResult = repository.getPoetryDetail(poetryId)
            withContext(Dispatchers.Main) {
                if (ksResult is KsResult.Success<PoetryDetail>) {
                    val uiModel =
                        LiveDataModel(
                            showLoading = false,
                            showError = null,
                            dataModel = ksResult.data
                        )
                    _uiState.value = uiModel
                } else if (ksResult is KsResult.Error){
                    val uiModel =
                        LiveDataModel(
                            showLoading = false,
                            showError = "网络异常",
                            dataModel = null
                        )
                    _uiState.value = uiModel
                }
            }
        }
    }
}